<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/5/20
 * Time: 16:16
 */
namespace app\api\controller;
use app\models\Models;
use app\service\Redis;
use app\service\Rsa;

class Login extends Base{
    /**
     * APP登录
     * */
    public function login(){
        if(request()->isPost()){
            $post  = input('param.');
            $rsa   = new Rsa();
            $redis = new Redis();
            $user  = new Models('user');
            try{
                // 签名验证
                self::sign($post,['equipment','encrypt']);
                // 获取解密后的数据
                $decrypt = $rsa->decrypt($post['equipment'],$post['encrypt']);
                // 场景验证
                $validate = self::validate($decrypt,'User.login');
                if(true !== $validate){
                    throw new \LogicException($validate,1016);
                }
                // 获取用户信息
                $info = $user->_find(['username'=>$decrypt['username']]);
                // 抛出异常信息
                self::errorMsg($info,$decrypt['password']);
                // 生成token
                $token = self::setToken($post['equipment'],$info['username'],$info['password']);
                // 将token存入redis
                $redis->set($token,30*24*3600,$info['id']);
                // 将设备号存入redis
                $redis->set($info['id'],30*24*3600,$post['equipment']);
                // 返回数据
                $result = ['token'=>$token];
            }catch(\LogicException $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($result));
        }
    }

    /**
     * APP退出
     */
    public function logout(){
        if(request()->isPost()){
            $redis = new Redis();
            try{
                // 获取参数
                $params = self::paramsSign();
                // 清空token
                $logout = $redis->del($params['token']);
                if(false === $logout){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
               return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult());
        }
    }

    /**
     * 忘记密码
     */
    public function forgetPassword(){
        if(request()->isPost()){
            $redis = new Redis();
            $user  = new Models('user');
            try{
                // 获取参数
                $params = self::paramsSign(['equipment','encrypt','code']);
                // 场景验证
                $validate = $this->validate($params,'User.forgetPassword');
                if(true !== $validate){
                    throw new \LogicException($validate,1016);
                }
                // 获取用户信息
                $info = self::getUserInfo(['username'=>$params['username']]);
                if(!$info){
                    throw new \LogicException('该用户尚未注册',1002);
                }
                // 比对验证码
                $code = $redis->get($info['username'].'forgetPassword');
                if(!$code || $params['code'] != $code){
                    throw new \LogicException('验证码错误',1020);
                }
                // 修改密码
                $bool = $user->_save(['id'=>$info['id'],'password'=>password_hash($params['password'],true)]);
                if(false === $bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult());
        }
    }

    /**
     * 抛出异常信息
     * @param $data
     * @param $hash
     */
    protected function errorMsg($data,$hash){
        if(!$data){
            throw new \LogicException('该用户尚未注册',1002);
        }
        if($data['status'] == Models::STATUS_OFF){
            throw new \LogicException('该账户已锁定',1014);
        }
        if(!password_verify($hash,$data['password'])){
            throw new \LogicException('请输入正确的密码',1019);
        }
    }
}